package com.dkm.orproject.dkmoa.action;

import com.alibaba.fastjson.JSON;
import com.dkm.orproject.dkmoa.domain.OaLog;
import com.dkm.orproject.dkmoa.domain.OaPersonnel;
import com.dkm.orproject.dkmoa.domain.OaRegularFlow;
import com.dkm.orproject.dkmoa.domain.OaWorkSummary;
import com.dkm.orproject.dkmoa.service.OaWorkSummaryService;
import com.dkm.orproject.dkmoa.service.flow.OaRegularFlowService;
import com.dkm.orproject.utils.jwt.login.UserLoginToken;
import com.dkm.orproject.utils.utils.Tools;
import io.swagger.annotations.*;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName : OaWorkSummaryAction  //类名
 * @Description : 工作总结Action  //描述
 * @Author : 易嵘  //作者
 * @Date: 2020-11-11 15:52  //时间
 */
@RestController
@RequestMapping("OaWorkSummaryAction")
@Api(tags = "工作总结")
public class OaWorkSummaryAction {

    /**
     * 工作总结服务接口
     */
    @Resource
    OaWorkSummaryService workSummaryService;

    /**
     * 工具类
     */
    @Resource
    Tools tools;


    /**
     * 回调值
     */
    int row=0;

    /**
     * 日志
     */
    OaLog log;

    /**
     * 登陆人
     */
    OaPersonnel personnel;

    /**
     * 回调map
     */
    Map<String,Object> map;

    /**
     * 分页查询
     * @param workSummaryName 工作总结模型 用于条件查询
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param page 当前页数
     * @param limit 显示的行数
     * @return 转正流程集
     */
    @ApiOperation(value = "工作总结分页查询接口", notes = "工作总结分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workSummaryName",value = "工作总结名称（模糊）",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "显示行数", required = true, dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaRegularFlow.class),
    })
    @UserLoginToken
    @GetMapping("findAll")
    public Map<String,Object> findAll(String workSummaryName,
                                      String isAll,
                                      String startTime,
                                      String endTime,
                                      Integer page,
                                      Integer limit,
                                      HttpServletRequest request){
        //获取当前操作人信息
        rowMap(request);
        //判断操作人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            return null;
        }
        try{
            List<OaWorkSummary> dataDictionaries;
            Long rowCount;
            if("1".equals(isAll)){
                //批量查询分页
                dataDictionaries=workSummaryService.findAll(workSummaryName,personnel.getPkPersonnelId(),startTime,endTime,page,limit);
                //查询总行数
                rowCount=workSummaryService.rowCount(workSummaryName,personnel.getPkPersonnelId(),startTime,endTime);
            }else{
                //批量查询分页
                dataDictionaries=workSummaryService.findAll(workSummaryName,null,startTime,endTime,page,limit);
                //查询总行数
                rowCount=workSummaryService.rowCount(workSummaryName,null,startTime,endTime);
            }

            //格式化返回参数
            return Tools.maps(dataDictionaries,rowCount);
        }catch (Exception e){
            //报错信息收集
            addErrorLog(request,"转正流程分页查询",e);
        }
        return null;

    }

    /**
     * id查询
     * @param id 工作总结主键
     * @return 工作总结模型
     */
    @ApiOperation(value = "id查询", notes = "id查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "工作总结id",dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK",response = OaRegularFlow.class),
    })
    @UserLoginToken
    @GetMapping("findById/{id}")
    public OaWorkSummary findById(@PathVariable("id") Long id, HttpServletRequest request){
        //获取当前操作人信息
        rowMap(request);
        //判断操作人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            return null;
        }
        try{
            //id查询
            return workSummaryService.selectByPrimaryKey(id);
        }catch (Exception e){
            //报错信息收集
            addErrorLog(request,"工作总结id查询",e);
        }
        return null;
    }

    /**
     * 收集报错日志
     * @param request 请求 用于得到当前登录人和ip地址
     * @param title 模块标题
     * @param e 异常参数
     */
    private void addErrorLog(HttpServletRequest request,String title,Exception e){
        //后台打印报错信息
        e.printStackTrace();
        //获取当前操作人
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //新建日志
        log=new OaLog();
        //日志类型
        log.setLogType("0");
        //日志内容
        log.setLogBody(e.getLocalizedMessage());
        //日志标题
        log.setLogTitle(title);
        //请求地址
        log.setLogIp(request.getRemoteAddr());
        //判断当前登陆人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            //当前操作人名称
            log.setCreatedBy(personnel.getPersonnelName());
        }
        //存入报错日志
        tools.errorMap(log);
    }

         /**
         * 工作总结新增
         * @param workSummary 工作总结模型
         * @param request 服务器请求
         * @return 回调函数
         */
        @ApiOperation(value = "工作总结新增", notes = "工作总结新增")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "workSummary",value = "工作总结模型",dataType = "Date",paramType = "query"),
                @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
        })
        @ApiResponses({
                @ApiResponse(code = 200,message = "提交成功"),
        })
        @UserLoginToken
        @PostMapping("add")
        public Map<String,Object> add(OaWorkSummary workSummary, HttpServletRequest request,Long select){
            //获取当前操作人
            rowMap(request);
            //判断当前操作人是否存在
            if(ObjectUtils.isEmpty(personnel)){
                return tools.rowMap(map,0,null);
            }
        try{
            if(!ObjectUtils.isEmpty(select)){
                workSummary.setWorkSummaryTypeId(select);
            }
            if(workSummary.getPkWorkSummaryId()==null || workSummary.getPkWorkSummaryId() < 1L){
                workSummary.setPersonnelId(personnel.getPkPersonnelId());
                //工作总结新增
                row=workSummaryService.add(workSummary,personnel.getPersonnelName());
            }else{
                // 修改人
                workSummary.setUpdatedBy(personnel.getPersonnelName());
                // 修改时间
                workSummary.setUpdatedTime(new Date());
                //方法修改
                row=workSummaryService.updateByPrimaryKeySelective(workSummary);
            }

            //日志标题
            log.setLogTitle("工作总结新增");
            //日志类型
            log.setLogType("1");
            //日志内容
            log.setLogBody(JSON.toJSON(workSummary).toString());
            //存入日志信息 格式化返回信息
            tools.rowMap(map,row,log);
        }catch (Exception e){
            //报错信息收集
            addErrorLog(request,"工作总结新增",e);
        }
        return map;
    }

    /**
     * 批量删除
     * @param ids 工作总结id集
     * @param request 服务器请求
     * @return 回调函数
     */
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "工作总结批量id",dataType = "Long[]",paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "提交成功"),
    })
    @UserLoginToken
    @DeleteMapping("deleteAll")
    public Map<String,Object> deleteAll(@RequestParam(value = "ids[]",required = false) Long[] ids,HttpServletRequest request){
        //获取当前登录人信息
        rowMap(request);
        //判断当前登陆人是否存在
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            //数组转化为集合
            List<Long> list= Arrays.asList(ids);
            //查询要删除得数据
            List<OaWorkSummary> dataDictionaries=workSummaryService.selectAll(list);
            //批量删除工作总结
            row=workSummaryService.deleteAll(list);
            //日志标题
            log.setLogTitle("转正流程批量删除");
            //日志内容
            log.setLogBody(JSON.toJSON(dataDictionaries).toString());
            //日志类型
            log.setLogType("1");
            //新增日志信息格式化返回值给前台
            tools.rowMap(map,row,log);
        }catch (Exception e){
            //收集错误信息
            addErrorLog(request,"转正流程批量删除",e);
        }
        return map;
    }

    /**
     * id删除
     * @param id 转正流程id
     * @param request 服务器请求
     * @return 回调函数
     */
    @ApiOperation(value = "id删除", notes = "id删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "转正流程id",dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "删除成功"),
    })
    @UserLoginToken
    @DeleteMapping("deleteById/{id}")
    public Map<String,Object> deleteById(@PathVariable(value = "id",required = false)Long id,HttpServletRequest request){
        rowMap(request);
        if(ObjectUtils.isEmpty(personnel)){
            return tools.rowMap(map,0,null);
        }
        try{
            //根据id查询
            OaWorkSummary flow=workSummaryService.selectByPrimaryKey(id);
            //根据id删除
            row=workSummaryService.deleteByPrimaryKey(id);
            //日志标题
            log.setLogTitle("转正流程删除");
            //日志内容
            log.setLogBody(JSON.toJSON(flow).toString());
            //日志类型
            log.setLogType("1");
            //新增日志信息 格式化返回参数
            tools.rowMap(map,row,log);
        }catch (Exception e){
            addErrorLog(request,"转正流程删除",e);
        }
        return map;
    }

    /**
     * 优化代码 获取当前登陆人信息
     * @param request 服务器请求
     */
    private void rowMap(HttpServletRequest request){
        //新建返回Map模型
        map=new HashMap<>(16);
        //获取登陆人信息
        personnel= (OaPersonnel) request.getSession().getAttribute("user");
        //为空则清空map
        if(ObjectUtils.isEmpty(personnel)){
            return;
        }
        //新建日志
        log=new OaLog();
        //得到ip
        log.setLogIp(request.getRemoteAddr());
        //登陆人名称
        log.setCreatedBy(personnel.getPersonnelName());
    }

    /**
     * 日期格式化
     *
     * @param binder 服务器参数转换器
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // true:允许输入空值，false:不能为空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
